package com.wiselink.naver.productcatalog;

import com.alibaba.fastjson2.JSONObject;
import com.wiselink.exception.NaverException;
import com.wiselink.naver.productcatalog.response.RegisterProductResponse;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Objects;

public class RegisterProducts {
    private static final Logger log = LoggerFactory.getLogger(RegisterProducts.class);

    public static RegisterProductResponse execute(String content, String accessToken) {
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, content);
        Request request = new Request.Builder()
                .url("https://api.commerce.naver.com/external/v2/products")
                .post(body)
                .addHeader("Authorization", accessToken)
                .addHeader("content-type", "application/json")
                .build();

        try (Response response = client.newCall(request).execute()) {
            int code = response.code();
            log.info("code: {}", code);
            String bodyStr = null;
            if (response.body() != null) {
                bodyStr = response.body().string();
            }
            log.error("Response.body: {}", bodyStr);
            if (code == 200) {
                return JSONObject.parseObject(bodyStr, RegisterProductResponse.class);
            } else {
                try {
                    JSONObject object = JSONObject.parseObject(bodyStr);
                    if (Objects.nonNull(object)) {
                        log.error("code: {}, message: {}", object.getString("code"), object.getString("message"));
                    }
                } catch (Exception ignored) {
                }
                throw new NaverException("RegisterProduct fail, reason: " + bodyStr);
            }
        } catch (IOException e) {
            log.error("RegisterProduct error", e);
            throw new NaverException("RegisterProduct error");
        }
    }
}
